//
//  QRCodeViewController.swift
//  weibopush
//
//  Created by 龚欣 on 15/6/29.
//  Copyright © 2015年 gong. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewController: UIViewController,UITabBarDelegate,AVCaptureMetadataOutputObjectsDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        setUpNaviBar()
        tabBar.selectedItem = tabBar.items![0]
        
        
        setUpSession()
        setUpLayers()
    }
    
    func setUpNaviBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
    }
    
    func dismiss(){
        dismissViewControllerAnimated(true, completion: nil)
    }

   
    @IBOutlet weak var scanLineView: UIImageView!
    @IBOutlet weak var widthConstraint: NSLayoutConstraint!
    @IBOutlet weak var heightConstraint: NSLayoutConstraint!
    @IBOutlet weak var scanlineTopConstraint: NSLayoutConstraint!
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        scanlineAnimation()
        startScaning()
    }
    
    func scanlineAnimation(){
        scanlineTopConstraint.constant = -heightConstraint.constant
        view.layoutIfNeeded()
        UIView.animateWithDuration(1.5) { () -> Void in
            UIView.setAnimationRepeatCount(MAXFLOAT)
            self.scanlineTopConstraint.constant = self.heightConstraint.constant
            self.view.layoutIfNeeded()
        }
    }
    
    @IBOutlet weak var tabBar: UITabBar!
    func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
        tabBar.selectedItem = item
        self.heightConstraint.constant = self.widthConstraint.constant * (item.tag == 0 ? 1 : 0.5)
        scanLineView.layer.removeAllAnimations()
        scanlineAnimation()
    }
    
    lazy var session : AVCaptureSession = AVCaptureSession()
    
    @IBOutlet weak var resultLabel: UILabel!
    lazy var inputDevice : AVCaptureDeviceInput? = {
        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        do {
            return try AVCaptureDeviceInput(device: device)
        }catch{
            return nil
        }
        }()
    
    lazy var dataOutPut : AVCaptureMetadataOutput = AVCaptureMetadataOutput()
    
    lazy var previewLayer : AVCaptureVideoPreviewLayer =  AVCaptureVideoPreviewLayer(session: self.session)
    
    lazy var drawLayer : CALayer = CALayer()
    
    func setUpSession(){
        
        if !session.canAddInput(inputDevice){
            print("无法添加设备")
            return
        }
        if !session.canAddOutput(dataOutPut){
            print("无法输出数据")
            return
        }
        
        session.addInput(inputDevice)
        print("前\(dataOutPut.availableMetadataObjectTypes)")
        session.addOutput(dataOutPut)
        print("后\(dataOutPut.availableMetadataObjectTypes)")

        
        dataOutPut.metadataObjectTypes = dataOutPut.availableMetadataObjectTypes
        
        dataOutPut.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
    }
    //AVCaptureMetadataOutputObjectsDelegate代理方法
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects: [AnyObject]!, fromConnection: AVCaptureConnection!){
        
        clearDrawLayer()
        
        for object in didOutputMetadataObjects{
            if object is AVMetadataMachineReadableCodeObject{
                let codeObject = previewLayer.transformedMetadataObjectForMetadataObject(object as! AVMetadataObject) as! AVMetadataMachineReadableCodeObject
                print(codeObject)
                resultLabel.text = codeObject.stringValue
                drawCorners(codeObject)
            }
        }
    }
    
    func clearDrawLayer(){
    
        if drawLayer.sublayers == nil{
            return
        }
        for layer in drawLayer.sublayers!{
            layer.removeFromSuperlayer()
        }
    
    }
    
    ///  绘制形变形状
    func drawCorners(codeObject : AVMetadataMachineReadableCodeObject){
    
        let layer = CAShapeLayer()
        layer.lineWidth = 4
        layer.lineJoin = kCALineJoinRound
        layer.strokeColor = UIColor.greenColor().CGColor
        layer.fillColor = UIColor.clearColor().CGColor
        layer.path = creatPath(codeObject.corners).CGPath
        
        drawLayer.addSublayer(layer)
    }
    
    //根据数组里面的point创建path
    func creatPath(corners : NSArray) -> UIBezierPath{
        let path = UIBezierPath()
        
        var point = CGPoint()
        var index = 0
        
        CGPointMakeWithDictionaryRepresentation(corners[index++] as! CFDictionary, &point)
        path.moveToPoint(point)
        
        while index < corners.count{
        CGPointMakeWithDictionaryRepresentation(corners[index++] as! CFDictionary, &point)
            path.addLineToPoint(point)
            
        }
        path.closePath()
    
        return path
    }
    
    //开始扫描
    func startScaning(){
    
        session.startRunning()
    }
    
    //设定展示layer 和 显示二维码边框的layer
    func setUpLayers(){
    
        drawLayer.frame = view.bounds
       view.layer.insertSublayer(drawLayer, atIndex: 0)
        
        previewLayer.frame = view.bounds
        
        previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
        
        view.layer.insertSublayer(previewLayer, atIndex: 0)
    }
    
    @IBAction func jumpToMyCard(sender: UIButton) {
        navigationController?.showViewController(MyQRCodeViewController(), sender: nil)
        
    }
    
}
